/**
 * Created by xiniu on 2017/8/30.
 */

import React, {Component, PropTypes} from 'react';
import {
    Image,
    StyleSheet,
    Text,
    View,
    ScrollView,
    TextInput,
    Modal,
    Dimensions,
    TouchableOpacity,
    NativeModules,
    Platform
} from 'react-native';

import Toast from "react-native-simple-toast";
import AppService from "../service/AppService";
import ImagePicker from "react-native-image-picker";

import MySuggestList from './MySuggestList';
import CoordinationList from './CoordinationList';
import SuggestContent from './components/SuggestContent';
import CommentList from './components/CommentList';
import RString from '../language/RString';

export default class suggestClose extends Component {
    // 初始化
    constructor(props){
        super(props);
        this.state = {
            isProject:false,
            title: RString('handle_suggest'),
            dealMethod:'',
            projectSummary:'',
            projectProfit:'',
            userId:'',
            userName: '',
            suggestId:this.props.id,
            suggest:{},
            showPicker:true,
            showProfitPicker:true,
            projectImgList:[],
            projectUploadList:[],
            profitImgList:[],
            profitUploadList:[],
            modalShow:false,
            filePath:null,
            profitModalShow:false,
            profitFilePath:null,
            completeImgIdList:[],
            completeUploadIdList:[],
            projectIncomeList:[],
            projectIncomeResult:[]
        };
    };

    componentWillMount() {
    //获取项目收益数据
      AppService.searchProjectIncome({ pageSize: 0, tenantId: global.tenantId,dbType:1 }).then((data) => {
                this.setState({
                   projectIncomeList: data.result,
                 });
          });
    }

    judgeProject(suggest){
        this.setState({
            isProject: suggest.isProject,
            suggest:suggest
        });
    };

    goBack = () => {
        const{navigator} = this.props;
        if(navigator){
            navigator.pop();
        }
    };

    doClose = () => {
        NativeModules.system.navTo("BACK");
    };

    // 非空校验
    checkComplete = (suggest) =>{
        if(suggest.hasOwnProperty('dealMethod')) {
            if(suggest.dealMethod == null || suggest.dealMethod.trim() == ""){
                Toast.show(RString('input_completion'));
                return false;
            } else {
                return true;
            }
        } else if(suggest.hasOwnProperty('projectSummary')) {
            if(suggest.projectSummary == null || suggest.projectSummary.trim() == ""){
                Toast.show(RString('input_overview'));
                return false;
            }else if(suggest.projectProfit == null || suggest.projectProfit.trim() == ""){
                Toast.show(RString('input_profit'));
                return false;
            }else{
                return true;
            }
        }
    };

    suggestClose = () => {
        let _this = this;
        let vm = {
            dealMethod:this.state.dealMethod
        }
        if(this.checkComplete(vm)) {
            if (this.state.dealMethod && this.state.dealMethod.length > 500) {
                Toast.show(RString('max_completion'));
            } else {
                const {navigator} = this.props;
                let vm = {
                    businessId: this.state.suggestId,
                    businessType: 'DOCK',
                    anonymous: false,
                    userId: global.userId,
                    content: global.userName + RString('suggest_close')
                };

                //　创建评论
                AppService.createCommentRecord(vm).then(data => {
                    if (!!data.errors === true && !!data.errors.length > 0) {
                        Toast.show(data.errors[0].message);
                    } else {
                        let suggest = {
                            id: _this.state.suggest.id,
                            dealMethod: _this.state.dealMethod
                        };
                        AppService.updateToClose(suggest).then(res => {
                            if (!!res.errors === true && !!res.errors.length > 0) {
                                Toast.show(res.errors[0].message);
                            } else {
                                Toast.show(RString('recommend_close'));
                                if (navigator) {
                                    if (global.isCoordinator) {
                                        navigator.push({
                                            name: "CoordinationList",
                                            component: CoordinationList
                                        })
                                    } else {
                                        navigator.push({
                                            name: "MySuggestList",
                                            component: MySuggestList
                                        });
                                    }
                                }
                            }
                        });
                    }
                });
            }
        }
    };

    doComplete = () => {
        let _this = this;
        let vm = {
            projectSummary:this.state.projectSummary,
            projectProfit:this.state.projectProfit,
        }
        if(this.checkComplete(vm)) {
            if (this.state.projectSummary && this.state.projectSummary.length > 200) {
                Toast.show(RString('max_overview'));
            } else if (this.state.projectProfit && this.state.projectProfit.length > 200) {
                Toast.show(RString('max_profit'));
            } else {
                var item = "";
                if(this.state.projectIncomeResult.length>0){
                    for(var i=0; i<this.state.projectIncomeResult.length; i++){
                        if(this.state.projectIncomeResult[i]==null||this.state.projectIncomeResult[i].length==0){

                        }else{
                            item = item + this.state.projectIncomeResult[i] + ";";
                        }

                    }
                }
                if(this.state.projectIncomeList.length>0){
                    if(item==null||item.length==0){
                        Toast.show(RString('input_profit'));
                        return;
                    }
                }
                if(item==null||item.length==0){
                    item = "无"
                }

                const {navigator} = this.props;
                let vm = {
                    businessId: this.state.suggestId,
                    businessType: 'DOCK',
                    anonymous: false,
                    userId: global.userId,
                    content: global.userName + RString('complete_suggest')
                };
                //　创建评论

                AppService.createCommentRecord(vm).then(data => {
                    if (!!data.errors === true && !!data.errors.length > 0) {
                        Toast.show(data.errors[0].message);
                    } else {
                        let suggest = {
                            id: _this.state.suggest.id,
                            projectSummary: _this.state.projectSummary,
                            projectProfit: _this.state.projectProfit,
                            projectProfitConfig:item
                        };
                        AppService.completeProject(suggest).then(response => {
                            if (!!response.errors === true && !!response.errors.length > 0) {
                                Toast.show(response.errors[0].message);
                            } else {
                                Toast.show(RString('project_success'));
                                if (navigator) {
                                    if (global.isCoordinator) {
                                        navigator.push({
                                            name: "CoordinationList",
                                            component: CoordinationList
                                        })
                                    } else {
                                        navigator.push({
                                            name: "MySuggestList",
                                            component: MySuggestList
                                        });
                                    }
                                }
                            }
                        });
                    }
                });

            }
        }
    };

    // 上传图片
    selectImage() {
        var that = this;
        if(that.state.projectImgList.length >= 2){
            that.setState({
                showPicker:false
            });
        }
        const options = {
            title: RString('chooseHeadImg'),
            storageOptions: {
                skipBackup: true,
                path: 'images',
                waitUntilSaved: true,
            },
            cancelButtonTitle: RString('cancel'),
            takePhotoButtonTitle: RString('takePhoto'),
            chooseFromLibraryButtonTitle: RString('chooseAlbum'),
            quality: 1,
            noData: true,
            maxWidth: 700,
            maxHeight: 700,
        };
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                console.warn('User cancelled image picker');
            }
            else if (response.error) {
                console.warn('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.warn('User tapped custom button: ', response.customButton);
            }
            else {
                let file = {
                    uri: '',
                    name: 'photo',
                    type: 'image/jpeg',
                };
                if(Platform.OS === 'android'){
                    file.uri = response.uri
                }else {
                    file.uri = response.uri.replace('file://', '')
                }
                AppService.uploadImage(file,global.passportId).then(response=>{
                    var rep = response;
                    if(!!rep.url && rep.url.length > 0){
                        AppService.uploadbyfileid({
                            fileId:rep.id,
                            businessId: that.state.suggestId,
                            businessType:"PROJECT",
                            businessCategory:"COMMON"
                        }).then(response=> {
                            that.state.completeImgIdList.push(response.attachment.id);
                            that.setState({
                                completeUploadIdList:that.state.completeImgIdList
                            });
                            that.state.projectUploadList.push(rep);
                            that.setState({
                                projectImgList:that.state.projectUploadList
                            });
                        });
                    }
                });
            }
        });
    }

    // 渲染图片
    renderImage = (v, i) =>{
        return (
            <View style={{ position:'relative' }} key={i}>
                <TouchableOpacity onPress={() => this.deleteImg(v.id,i)} style={styles.deleteImage}>
                    <Image source={require('./img/chahao.png')} style={{ width:10,height:10 }}/>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.enlargeImg(v.url)}>
                    <Image style={styles.uploadImg} source={{uri: v.url}}/>
                </TouchableOpacity>
            </View>
        )
    };

    // 删除图片
    deleteImg(idx,index){
        if(this.state.projectImgList.length <= 3){
            this.setState({
                showPicker:true
            });
        }
        let _this = this;
        let vm = {
            businessType:"PROJECT",
            businessId: this.state.suggestId
        };
        // 获取该提案的图片
        AppService.getUploadImage(vm).then(data =>{
            if (!!data.errors === true && !!data.errors.length > 0) {
                Toast.show(data.errors[0].message);
            } else {
                _this.setState({
                    projectImgList:data.attachmentList
                });
                for(var i = 0;i < _this.state.projectImgList.length;i++) {
                    if(idx === _this.state.projectImgList[i].fileId) {
                        AppService.deleteUploadImage({attachmentId:_this.state.projectImgList[i].id}).then(response=>{
                            if (!!response.errors === true && !!response.errors.length > 0) {
                                Toast.show(response.errors[0].message);
                            } else {
                                _this.state.projectUploadList.splice(index,1);
                                _this.setState({
                                    projectImgList:_this.state.projectUploadList
                                });
                            }
                        });
                    }
                }
            }
        });
    };

    // 放大图片
    enlargeImg(url) {
        this.setState({
            modalShow:true,
            filePath:url
        });
    }

    // 关闭弹窗
    closeModal() {
        this.setState({
            modalShow:false
        });
    }

    // 上传利润图片
    selectProfitImage() {
        var that = this;
        if(that.state.profitImgList.length >= 2){
            that.setState({
                showProfitPicker:false
            });
        }
        const options = {
            title: RString('chooseHeadImg'),
            storageOptions: {
                skipBackup: true,
                path: 'images',
                waitUntilSaved: true,
            },
            cancelButtonTitle: RString('cancel'),
            takePhotoButtonTitle: RString('takePhoto'),
            chooseFromLibraryButtonTitle: RString('chooseAlbum'),
            quality: 1,
            noData: true,
            maxWidth: 700,
            maxHeight: 700,
        };
        ImagePicker.showImagePicker(options, (response) => {
            if (response.didCancel) {
                console.warn('User cancelled image picker');
            }
            else if (response.error) {
                console.warn('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.warn('User tapped custom button: ', response.customButton);
            }
            else {
                let file = {
                    uri: '',
                    name: 'photo',
                    type: 'image/jpeg',
                };
                if(Platform.OS === 'android'){
                    file.uri = response.uri
                }else {
                    file.uri = response.uri.replace('file://', '')
                }
                AppService.uploadImage(file,global.passportId).then(response=>{
                    var rep = response;
                    if(!!rep.url && rep.url.length > 0){
                        AppService.uploadbyfileid({
                            fileId:rep.id,
                            businessId: that.state.suggestId,
                            businessType:"PROFIT",
                            businessCategory:"COMMON"
                        }).then(response=> {
                            that.state.completeImgIdList.push(response.attachment.id);
                            that.setState({
                                completeUploadIdList:that.state.completeImgIdList
                            });
                            that.state.profitUploadList.push(rep);
                            that.setState({
                                profitImgList:that.state.profitUploadList
                            });
                        });
                    }
                });
            }
        });
    }

    // 渲染利润图片
    renderProfitImage = (v, i) =>{
        return (
            <View style={{ position:'relative' }} key={i}>
                <TouchableOpacity onPress={() => this.deleteProfitImg(v.id,i)} style={styles.deleteImage}>
                    <Image source={require('./img/chahao.png')} style={{ width:10,height:10 }}/>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => this.enlargeProfitImg(v.url)}>
                    <Image style={styles.uploadImg} source={{uri: v.url}}/>
                </TouchableOpacity>
            </View>
        )
    };

    // 删除利润图片
    deleteProfitImg(idx,index){
        if(this.state.profitImgList.length <= 3){
            this.setState({
                showProfitPicker:true
            });
        }
        let _this = this;
        let vm = {
            businessType:"PROJECT",
            businessId: this.state.suggestId
        };
        // 获取该提案的图片
        AppService.getUploadImage(vm).then(data =>{
            if (!!data.errors === true && !!data.errors.length > 0) {
                Toast.show(data.errors[0].message);
            } else {
                _this.setState({
                    profitImgList:data.attachmentList
                });
                for(var i = 0;i < _this.state.profitImgList.length;i++) {
                    if(idx === _this.state.profitImgList[i].fileId) {
                        AppService.deleteUploadImage({attachmentId:_this.state.profitImgList[i].id}).then(response=>{
                            if (!!response.errors === true && !!response.errors.length > 0) {
                                Toast.show(response.errors[0].message);
                            } else {
                                _this.state.profitUploadList.splice(index,1);
                                _this.setState({
                                    profitImgList:_this.state.profitUploadList
                                });
                            }
                        });
                    }
                }
            }
        });
    };

    // 放大利润图片
    enlargeProfitImg(url) {
        this.setState({
            profitModalShow:true,
            profitFilePath:url
        });
    }

    // 关闭利润弹窗
    closeProfitModal() {
        this.setState({
            profitModalShow:false
        });
    }

    projectIncomeSet(event, id, i){
        var text = event.nativeEvent.text;
        if(text==null||text.length==0){
            this.state.projectIncomeResult[i]= "";
        }else{
            this.state.projectIncomeResult[i]= id + ":" + text;
        }

    }

    //项目收益
    projectIncome = (v, i) => (
        <View style={styles.imcomeDetail}  key={i}>
            <View style={{ justifyContent: 'center',flex: 1 }}>
                <Text style={{ color: '#000', fontSize: 12 }}>{v.projectIncomeName}</Text>
            </View>
            <View style={{ flex: 10}}>
                <TextInput
                    style={{ fontSize: 12 }}
                    placeholder='请填写项目收益'
                    underlineColorAndroid="transparent"
                    placeholderTextColor="#A9A9A9"
                    //onChangeText={text => this.setState({ projectIncomeResult: text})}
                    onChange ={(event)=>this.projectIncomeSet(event, v.id, i)}
                />
            </View>
            <View style={{ justifyContent: 'center',flex: 3 }}>
                <Text style={{ color: '#000', fontSize: 12 }}>{v.projectIncomeUnit}</Text>
            </View>
        </View>
    );

    render(){
        let content=null;
        if(!this.state.isProject) {
            content=
                <View style={{ flex:1 }}>
                    <View style={styles.comment}>
                        <Text style={{ color:'#000' }}>{RString('complete')}</Text>
                    </View>
                    <View style={{flex:1,paddingLeft:15,paddingRight:15,paddingTop:10}}>
                        <TextInput style={{flex:1}}
                                   placeholder={RString('fill_complete')}
                                   placeholderTextColor='#A9A9A9'
                                   underlineColorAndroid='transparent'
                                   multiline={true}
                                   numberOfLines={6}
                                   textAlignVertical="top"
                                   maxLength={500}
                                   onChangeText={(text)=> this.setState({dealMethod:text})}
                        />
                        <View style={styles.suggestImgWrap}>
                            {this.state.projectImgList.map((v, i) => this.renderImage(v, i))}
                            {this.state.showPicker && <TouchableOpacity onPress={()=>{this.selectImage()}}>
                                <Image style={styles.uploadImg} source={require('./img/addImage.png')}/>
                            </TouchableOpacity>}
                        </View>
                    </View>
                </View>
        } else {
            content=
                <View style={{ flex:1 }}>
                    <View style={styles.comment}>
                        <Text style={{ color:'#000' }}>{RString('project_overview')}</Text>
                    </View>
                    <View style={{flex:1,paddingLeft:15,paddingRight:15,paddingTop:10}}>
                        <TextInput style={{flex:1}}
                                   placeholder={RString('fill_overview')}
                                   placeholderTextColor='#A9A9A9'
                                   underlineColorAndroid='transparent'
                                   multiline={true}
                                   numberOfLines={6}
                                   textAlignVertical="top"
                                   onChangeText={(text)=> this.setState({projectSummary:text})}
                        />
                        <View style={styles.suggestImgWrap}>
                            {this.state.projectImgList.map((v, i) => this.renderImage(v, i))}
                            {this.state.showPicker && <TouchableOpacity onPress={()=>{this.selectImage()}}>
                                <Image style={styles.uploadImg} source={require('./img/addImage.png')}/>
                            </TouchableOpacity>}
                        </View>
                    </View>
                    <View style={styles.comment}>
                        <Text style={{ color:'#000' }}>{RString('project_profit')}</Text>
                    </View>
                    <View>
                        {this.state.projectIncomeList.map((v, i) => this.projectIncome(v, i))}
                    </View>
                    <View style={{flex:1,paddingLeft:15,paddingRight:15,paddingTop:10}}>
                        <TextInput style={{flex:1}}
                                   placeholder={RString('fill_profit')}
                                   placeholderTextColor='#A9A9A9'
                                   underlineColorAndroid='transparent'
                                   multiline={true}
                                   numberOfLines={6}
                                   textAlignVertical="top"
                                   onChangeText={(text)=> this.setState({projectProfit:text})}
                        />
                        <View style={styles.suggestImgWrap}>
                            {this.state.profitImgList.map((v, i) => this.renderProfitImage(v, i))}
                            {this.state.showProfitPicker && <TouchableOpacity onPress={()=>{this.selectProfitImage()}}>
                                <Image style={styles.uploadImg} source={require('./img/addImage.png')}/>
                            </TouchableOpacity>}
                        </View>
                    </View>
                </View>
        }
        return (
        <View style={{ position:'relative',flex:1 }}>
            <Modal
                animationType='slide'
                transparent={true}
                visible={this.state.modalShow}
                onShow={() => {}}
                onRequestClose={() => {}} >
                <TouchableOpacity activeOpacity={1} style={styles.modalLayout} onPress={()=>{this.closeModal()}}>
                    <Image style={styles.modalView}  source={{uri:this.state.filePath+"?x-oss-process=image/resize,m_lfit,w_640,h_640"}} resizeMode="contain"></Image>
                </TouchableOpacity>
            </Modal>
            <Modal
                animationType='slide'
                transparent={true}
                visible={this.state.profitModalShow}
                onShow={() => {}}
                onRequestClose={() => {}} >
                <TouchableOpacity activeOpacity={1} style={styles.modalLayout} onPress={()=>{this.closeProfitModal()}}>
                    <Image style={styles.modalView}  source={{uri:this.state.profitFilePath+"?x-oss-process=image/resize,m_lfit,w_640,h_640"}} resizeMode="contain"></Image>
                </TouchableOpacity>
            </Modal>
            <View style={styles.commonHeader}>
                <TouchableOpacity onPress={this.goBack.bind(this)} style={styles.back}>
                    <Image source={require('./img/leftArrow.png')} />
                </TouchableOpacity>
                <TouchableOpacity onPress={this.doClose.bind(this)} style={styles.toIndex}>
                    <Image source={require('./img/chahao.png')}/>
                </TouchableOpacity>
                <View style={{ justifyContent:'center' }}>
                    <Text style={{ color:'#fff',fontSize:16 }}>{this.state.title}</Text>
                </View>
            </View>
            <ScrollView style={styles.wrap}>
                <SuggestContent suggestId={this.state.suggestId} judgeProject={this.judgeProject.bind(this)}/>
                { content }
                <View style={{ flex:1,marginBottom:30 }}>
                    <View style={styles.comment}>
                        <Text style={{ color:'#000' }}>{RString('comment')}</Text>
                    </View>
                    <CommentList suggestId={this.state.suggestId}/>
                </View>
            </ScrollView>
            <View style={styles.buttonWrap}>
                <View style={{ flex:1,flexDirection:'row',justifyContent:'flex-end' }}>
                    <TouchableOpacity style={styles.distributeBtn} onPress={this.state.isProject?this.doComplete.bind(this):this.suggestClose.bind(this)}>
                        <Text style={{ color:'#fff' }}>{ this.state.isProject ? RString('project_complete') : RString('advise_close') }</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
        );
    };
}

const styles = StyleSheet.create({
    modalLayout:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height,
        backgroundColor:'rgba(0,0,0,.8)'
    },
    modalView:{
        width:Dimensions.get('window').width,
        height:Dimensions.get('window').height
    },
    wrap:{
        backgroundColor:'#fff'
    },
    commonHeader:{
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        backgroundColor:'#333238',
        flexDirection:'row',
        justifyContent:'center',
        position:'relative'
    },
    back:{
        width:30,
        position:'absolute',
        left:20,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    toIndex:{
        width:30,
        position:'absolute',
        left:70,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    detailWrap :{
        flex: 1,
        paddingLeft:10,
        paddingRight:10
    },
    detail : {
        paddingLeft:10,
        flexDirection: 'row'
    },
    detailTop:{
        paddingLeft:10,
        paddingRight:6,
        borderBottomWidth:1,
        borderStyle:'solid',
        borderBottomColor:'#eee',
        flexDirection: 'row'
    },
    imgWrap:{
        flex:1,
        justifyContent: 'center'
    },
    themeImg:{
        width:20,
        height:20
    },
    wordWrap:{
        flex:8,
        borderBottomWidth:1,
        borderStyle:'solid',
        borderBottomColor:'#eee',
        paddingTop:15,
        paddingBottom:15,
        flexDirection: 'row'
    },
    lastWordWrap:{
        flex:8,
        paddingTop:15,
        paddingBottom:15,
        flexDirection: 'row'
    },
    detailFont:{
        fontSize:16,
        color:'#000'
    },
    detailFontBold:{
        fontWeight:'bold',
        fontSize:16,
        color:'#000'
    },
    detailTime:{
        fontSize:14,
        color:'#999'
    },
    uploadImg:{
        width:80,
        height:80,
        marginRight:10,
        marginBottom:10
    },
    comment:{
        flex:1,
        height:25,
        paddingLeft:20,
        paddingRight:20,
        backgroundColor:'#ECECF1',
        justifyContent: 'center'
    },
    buttonWrap:{
        width:Dimensions.get('window').width,
        height:55,
        position:'absolute',
        left:0,
        bottom:0,
        backgroundColor:'#F5F5F5',
        paddingLeft:20,
        paddingRight:20,
        paddingTop:10,
        paddingBottom:10
    },
    distributeBtn:{
        width:100,
        borderRadius:5,
        paddingTop:8,
        paddingBottom:8,
        backgroundColor:'#3399FF',
        flexDirection:'row',
        justifyContent:'center'
    },
    projectImgWrap:{
        flex:1,
        paddingLeft:20,
        paddingRight:20,
        paddingTop:20,
        paddingBottom:10,
        flexDirection: 'row',
        flexWrap:'wrap'
    },
    suggestImgWrap:{
        flex:1,
        paddingLeft:5,
        paddingRight:5,
        paddingTop:15,
        paddingBottom:5,
        flexDirection: 'row',
        flexWrap:'wrap'
    },
    deleteImage:{
        width:20,
        height:20,
        position:'absolute',
        top:0,
        right:10,
        zIndex:2,
        backgroundColor:'rgba(0,0,0,.7)',
        paddingLeft:5,
        paddingRight:5,
        justifyContent:'center'
    },
    commentWrap:{
        flex:1,
        padding:20
    },

    imcomeDetail:{
        flexDirection:'row',
        marginLeft:20,
        // marginTop:10,
    },
});

